import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/base/page_constance.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/login/entity/sv_entity.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:shopping_group/utils/route_util.dart';

class ZfbHtmlBloc implements BlocBase {
  //  Stream来初始化数量的操作
  StreamController<Object> _initController = StreamController<Object>();
  //初始化动作
  StreamSink get initDate => _initController.sink;

  StreamController<Object> _resetController = StreamController<Object>();
  //初始化动作
  StreamSink get restDate => _resetController.sink;

  ZfbHtmlBloc() {
    _initController.stream.listen(initData);
    _resetController.stream.listen(restData);
  }

  void restData(data) {
    if (data is Map) {
      _resetTask(data);
    }
  }

  void initData(data) {
    if (data is Map) {
      _initTask(data);
    }
  }

  void _resetTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    // BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.HTML_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            SvEntity parm = SvEntity.fromJson(result);
            eventBus.fire(ZfbHtmlCloseEvent(parm.val));
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  void _initTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
   // BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.HTML_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            SvEntity parm = SvEntity.fromJson(result);
            eventBus.fire(ZfbHtmlEvent(parm.val));
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  @override
  void dispose() {
    _initController?.close();
    _resetController?.close();
  }
}
